<template>
  <base-modal
    class="sparepart-apply-dialog-container"
    :show.sync="visible"
    :title="title"
    width="900px"
  >
    <!-- start 出库方式 -->
    <div class="part-apply-method-panel" v-if="showApproveType">
      {{$t('task.detail.components.outStockMethod')}}：
      <el-radio-group v-model="params.approveType">
        <el-radio :label="5" v-if="showOutRepertoryPerson">{{$t('task.detail.components.applyPersonalPart')}}</el-radio>
        <el-radio :label="0" v-if="showOutRepertoryDirect">{{$t('common.form.preview.sparepart.des7')}}</el-radio>
      </el-radio-group>
    </div>
    <!-- end 出库方式 -->

    <part-service-table
      ref="sparepartTable"
      :data="data"
      :colums="columns"
      :can-select-part="!isOnlyPartOut"
      :part-config="partConfig"
      :card="card"
      v-if="visible"
    />

    <div class="btn-group" v-if="!isOnlyPartOut">
      <el-button type="primary" icon="el-icon-plus" plain size="mini" @click="addPart">{{$t('common.base.addModule', {module:''})}}</el-button>
    </div>

    <!-- 备注 -->
    <div class="apply-remark-panel">
      <el-input type="textarea" :rows="3" :placeholder="$t('task.detail.components.remarkPlaceholder')" v-model="params.remark"></el-input>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button :disabled="pending" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" :disabled="pending" @click="submit">{{$t('common.base.submit')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi';
import { checkNeedVipApprove, approveCreate } from '@src/api/SparepartApprove.ts';
/* components */
import PartSeviceTable from '@src/modules/task/editAllot/components/PartSeviceList/components/PartSeviceTable.vue';
/* enum */
import { TaskEventNameMappingEnum } from '@model/enum/EventNameMappingEnum.ts';
/* model */
import { PART_SERVICE_LIST_MAX_LENGTH } from '@src/model/const/Number';
import { PART_SERVICE_LIST_MAX_LENGTH_MESSAGE } from '@src/model/const/Alert';
/** util */
import { getRootWindow } from '@src/util/dom';

export default {
  name: 'spare-part-apply-dialog',
  props: {
    fields: {
      type: Array,
      default: () => ([])
    },
    // 备件配置
    partConfig: {
      type: Object,
      default: () => ({})
    },
    card: {
      type: Object,
      default: () => ({})
    },
    task: {
      type: Object,
      default: () => ({})
    },
    value: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      pending: false,
      visible: false,
      isOnlyPartOut: true, // false 选择备件并申请出库
      data: [],
      params: {},
      needVipApprove: false, // 是否需要高级审批
    }
  },
  computed: {
    /** 是否开启出入库审批设置 */
    isShowApprovalSetting() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.ADVANCED_APPROVAL_OF_SPARE_PARTS_GRAY ?? false;
    },
    title() {
      return this.isOnlyPartOut ? this.$t('common.form.type.outWarehouse') : this.$t('task.detail.components.chooseSparePart');
    },
    /** 备件清单附加组件配置 */
    cardConfig() {
      return JSON.parse(this.card.config || '{}');
    },
    /** 是否开启个人备件库 */
    personalRepertory() {
      return this.partConfig.personalRepertory;
    },
    /** 显示出库方式 */
    showApproveType() {
      return this.personalRepertory && (this.showOutRepertoryPerson || this.showOutRepertoryDirect);
    },
    /** 显示申领个人备件库 */
    showOutRepertoryPerson() {
      return (this.cardConfig.sparePartWhere || []).indexOf('taskOutRepertoryPerson') > -1;
    },
    /** 显示直接出库 */
    showOutRepertoryDirect() {
      return (this.cardConfig.sparePartWhere || []).indexOf('taskOutRepertoryDirect') > -1;
    },
    columns() {
      let fields = [
        ...this.fields.filter(item => item.fieldName != 'preNum' && item.fieldName != 'total'),
        {
          displayName: this.$t('task.detail.components.applyRepertory'),
          fieldName: 'repertory',
          width: '150px'
        },
        {
          displayName: this.$t('task.detail.components.repertoryCount'),
          fieldName: 'repertoryCount',
          width: '80px'
        },
        {
          displayName: this.$t('task.detail.components.personRepertoryCount'),
          fieldName: 'personRepertoryCount',
          width: '80px'
        },
        {
          displayName: this.$t('task.detail.components.applyNum'),
          fieldName: 'preNum',
          width: '120px'
        },
        {
          displayName: this.$t('common.base.operation'),
          fieldName: 'action'
        }
      ]

      // 设置备件名称列宽
      fields.forEach(field => {
        if (field.fieldName == 'name') {
          field.width = '150px';
        }
      })

      // 未开启个人备件库时 不显示个人库存
      if (!this.personalRepertory) {
        fields = fields.filter(field => field.fieldName != 'personRepertoryCount');
      }

      return fields;
    }
  },
  methods: {
    buildParams() {
      let { id, taskNo } = this.task;

      // 开启个人备件库，出库方式默认选中申领到个人库
      return {
        taskNo,
        taskId: id,
        remark: '',
        spareparts: [],
        taskCardId: this.card.cardId,
        approveType: this.personalRepertory ? 5 : 0,
        businessInfo: JSON.stringify({taskId: id, taskNo})
      }
    },
    /**
    * @description 打开弹窗
    */
    open(isOnlyPartOut = true, data = []) {
      this.isOnlyPartOut = isOnlyPartOut;
      this.data = data;

      this.params = this.buildParams();

      this.pending = false;
      this.visible = true;

      if (!isOnlyPartOut) {
        this.$nextTick(() => {
          // 默认添加一行数据
          this.addPart();
        })
      } else {
        let ids = this.data.map(item => {
          item.relationId = item.id;
          item.id = item.relatedId;
          return item.id;
        })

        this.$nextTick(() => {
          // 获取备件可用仓库列表
          this.$refs.sparepartTable.getRepertoryBySparePartIds(ids);
        })
      }
      
      if(this.isShowApprovalSetting) {
        this.checkNeedVipApproveReq();
      }
    },
    /**
    * @description 添加备件
    */
    addPart() {
      this.$refs.sparepartTable.add();
    },
    /**
    * @description 提交
    */
    async submit() {
      // 过滤掉空数据
      let selectedData = this.data.filter(item => item.id);
      if (selectedData.length == 0) return this.$platform.alert(this.$t('common.form.tip.sparepart.tips1'));

      // 仓库必填校验
      let isEmptyRepertoryArr = this.data.filter(item => item.id && !item.repertoryId);
      if (isEmptyRepertoryArr.length) return this.$platform.alert(this.$t('task.tip.sparePartApplyTip1', {msg: isEmptyRepertoryArr[0].name}));

      // 校验申请数量
      let isNumErrorArr = this.data.filter(item => item.id && (Number(item.preNum) > Number(item.repertoryCount)));
      if (isNumErrorArr.length) return this.$platform.alert(this.$t('task.tip.sparePartApplyTip2', {msg: isNumErrorArr[0].name}));

      // 添加备件并申领
      if (!this.isOnlyPartOut) {
        // 是否超过最大限制
        let isOverLimit = this.value.length + selectedData.length > PART_SERVICE_LIST_MAX_LENGTH;
        if (isOverLimit) return this.$platform.alert(PART_SERVICE_LIST_MAX_LENGTH_MESSAGE);
      }

      // 根据仓库id去重
      let spareparts = this.arrayUnique(this.data, 'repertoryId');
      let isMutiRepertory = spareparts.length > 1;
      let warnMsg = isMutiRepertory ? this.$t('task.tip.sparePartApplyTip3') : this.$t('task.tip.sparePartApplyTip4')

      const res_ = await this.$platform.confirm(this.$t('task.tip.sparePartApplyTip5', {msg: warnMsg}));
      if (!res_) return;

      this.params.spareparts = [];
      selectedData.forEach(item => {
        this.params.spareparts.push({
          sparepartId: item.id,
          repertoryId: item.repertoryId,
          num: Number(item.preNum),
          inventoryId: item.relationId,
          relationName: item.name
        })
      })

      this.pending = true;

      // 工单销售高级审批出库(直接出库除外)
      if(this.needVipApprove && this.params.approveType !== 0) return this.approveCreateReq(this.params)

      let api = this.isOnlyPartOut ? 'addInventoryApply' : 'addInventoryAndApply';
      TaskApi[api](this.params)
        .then(res => {
          if (res.success) {
            this.$platform.notification({
              type: 'success',
              title: this.$t('common.base.submitSuccess')
            })
            
            this.$parent.getInventoryByCardId();
            this.visible = false;

            this.$eventBus.$emit(TaskEventNameMappingEnum.UpdateRecord);
          } else {
            this.$platform.alert(res.message);
            this.pending = false;
          }
        }).catch(err => {
          this.pending = false;
        })
    },
    arrayUnique(arr, name) {
      let hash = {};
      return arr.reduce(function (item, next) {
        hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
        return item;
      }, []);
    },
    /** 校验是否需要发起审批 */
    async checkNeedVipApproveReq() {
      try {
        const params = {
          type: 2,
        }
        const { code, result} = await checkNeedVipApprove(params)
        if(code == 0) {
          this.needVipApprove = result.needVipApprove || false;
        }
      } catch (error){
        console.log(error)
      }
    },
    /** 发起办理出库(高级审批) */
    async approveCreateReq(applyParams) {
      try {
        const params = {
          action: "新建",
          applyRemark: "",
          inventoryApproveForm: applyParams,
          inventoryApproveType: this.isOnlyPartOut ? 2: 1,
          taskId: this.task.id,
        }
        const { code, result, message} = await approveCreate(params)
        if(code !== 0) return this.$message.warning(message);
        this.handleSuccess()
      } catch (error){
        console.log(error)
      } finally {
        this.visible = false;
      }
    },
    /**
    * @description 处理成功
    */
    handleSuccess() {
      this.$platform.notification({
        type: 'success',
        title: this.$t('common.base.submitSuccess')
      })
      
      this.$parent.getInventoryByCardId();
      this.visible = false;
      this.$eventBus.$emit(TaskEventNameMappingEnum.UpdateRecord);
    }
  },
  components: {
    [PartSeviceTable.name]: PartSeviceTable
  }
}
</script>

<style lang="scss" scoped>
.sparepart-apply-dialog-container {
  ::v-deep .base-modal-body {
    padding: 16px 0 !important;
  }

  .part-apply-method-panel {
    padding: 0 16px 16px;

    .el-radio {
      color: $text-color-regular;
      margin-right: 24px;
    }
  }

  .btn-group {
    text-align: center;
    margin-top: 16px;
    padding: 0 12px !important;

    .el-button {
      width: 72px !important;
    }
  }

  .apply-remark-panel {
    padding: 32px 16px;
  }
}
</style>